package org.achievement.system.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.achievement.system.common.RequestResult;
import org.achievement.system.common.annotations.InterfaceAuth;
import org.achievement.system.common.enums.AuthEnum;
import org.achievement.system.common.exception.ServiceException;
import org.achievement.system.dao.RoleDao;
import org.achievement.system.dao.ScoreDao;
import org.achievement.system.dao.UserDao;
import org.achievement.system.pojo.entity.Role;
import org.achievement.system.pojo.entity.Score;
import org.achievement.system.pojo.entity.User;
import org.achievement.system.pojo.excel.ScoreExcel;
import org.achievement.system.pojo.form.ScoreForm;
import org.achievement.system.service.ScoreService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

import static org.achievement.system.controller.CommonController.commonSetting;

@RestController
@RequestMapping("/score")
public class ScoreController {


    @Autowired
    private ScoreService scoreService;
    @Autowired
    private ScoreDao scoreDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private UserDao userDao;

    /**
     * 页面
     *
     * @param modelAndView
     * @return
     */
    @InterfaceAuth({AuthEnum.ADMIN, AuthEnum.TEACHER, AuthEnum.STUDENT})
    @RequestMapping()
    public ModelAndView index(ModelAndView modelAndView) {
        modelAndView.setViewName("score");
        commonSetting(modelAndView);
        return modelAndView;
    }

    /**
     * 查询
     *
     * @param scoreForm
     * @return
     */
    @InterfaceAuth({AuthEnum.ADMIN, AuthEnum.TEACHER, AuthEnum.STUDENT})
    @RequestMapping("/list")
    public RequestResult list(HttpServletRequest request, @RequestBody ScoreForm scoreForm) {
        String username = (String) request.getSession().getAttribute("username");
        User user = userDao.selectOne(new QueryWrapper<User>().eq("username", username));
        Role role = roleDao.selectOne(new QueryWrapper<Role>().eq("id", user.getRoleId()));
        if ("学生".equals(role.getName())) {
            scoreForm.setUserId(user.getId());
        }
        return scoreService.list(scoreForm);
    }

    /**
     * 统计
     *
     * @param scoreForm
     * @return
     */
    @InterfaceAuth({AuthEnum.ADMIN, AuthEnum.TEACHER, AuthEnum.STUDENT})
    @RequestMapping("/count")
    public RequestResult count(@RequestBody ScoreForm scoreForm) {
        Integer count = scoreDao.count(scoreForm);
        return RequestResult.success(count);
    }

    /**
     * 增加
     *
     * @param score
     * @return
     */
    @InterfaceAuth({AuthEnum.ADMIN, AuthEnum.TEACHER})
    @RequestMapping("/add")
    public RequestResult add(@RequestBody Score score) {
        if (score == null) {
            throw new ServiceException("不能提交空数据！");
        }
        if (score.getUserId() == null) {
            throw new ServiceException("用户不能为空！");
        }
        if (score.getCourseId() == null) {
            throw new ServiceException("课程不能为空！");
        }
        if (score.getScore() == null) {
            throw new ServiceException("分数不能为空！");
        }
        long count = scoreService.count(
                new QueryWrapper<Score>()
                        .eq("course_id", score.getCourseId())
                        .eq("user_id", score.getUserId()));
        if (count > 0) {
            throw new ServiceException("请勿重复录入分数！");
        }
        boolean save = scoreService.save(score);
        if (! save) {
            throw new ServiceException("保存失败！");
        }
        return RequestResult.success("提交成功！");
    }

    /**
     * 修改
     *
     * @param score
     * @return
     */
    @InterfaceAuth({AuthEnum.ADMIN, AuthEnum.TEACHER})
    @RequestMapping("/edit")
    public RequestResult edit(@RequestBody Score score) {
        if (score == null) {
            throw new ServiceException("不能提交空数据！");
        }
        if (score.getUserId() == null) {
            throw new ServiceException("用户不能为空！");
        }
        if (score.getCourseId() == null) {
            throw new ServiceException("课程不能为空！");
        }
        if (score.getScore() == null) {
            throw new ServiceException("分数不能为空！");
        }
        boolean save = scoreService.updateById(score);
        if (! save) {
            throw new ServiceException("保存失败！");
        }
        return RequestResult.success("提交成功！");
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @InterfaceAuth({AuthEnum.ADMIN, AuthEnum.TEACHER})
    @RequestMapping("/delete")
    public RequestResult delete(@RequestBody List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new ServiceException("请先选择！");
        }
        boolean removed = scoreService.removeBatchByIds(ids);
        if ( ! removed) {
            throw new ServiceException("删除失败！");
        }
        return RequestResult.success("删除成功！");
    }



    /**
     * 删除
     *
     * @param request
     * @param scoreForm
     * @return
     */
    @InterfaceAuth({AuthEnum.ADMIN, AuthEnum.TEACHER, AuthEnum.STUDENT})
    @RequestMapping("/export")
    public void export(HttpServletRequest request, HttpServletResponse response, @RequestBody ScoreForm scoreForm) throws IOException {
        String username = (String) request.getSession().getAttribute("username");
        User user = userDao.selectOne(new QueryWrapper<User>().eq("username", username));
        Role role = roleDao.selectOne(new QueryWrapper<Role>().eq("id", user.getRoleId()));
        if ("学生".equals(role.getName())) {
            scoreForm.setUserId(user.getId());
        }
        List<ScoreExcel> scoreExcels = scoreDao.listAll(scoreForm);
        if (scoreExcels == null || scoreExcels.isEmpty()) {
            throw new ServiceException("没有需要导出的数据！");
        }

        String originName = "成绩_" + System.currentTimeMillis() + ".xlsx";
        String fileName = URLEncoder.encode(originName , "UTF-8").replaceAll("\\+", "%20");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        EasyExcel.write(response.getOutputStream(), ScoreExcel.class)
                .sheet("sheet1")
                .doWrite(scoreExcels);
    }



}